package cn.net.xuefei.king;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerNativeActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.net.xuefei.king.plugins.WeChat;

public class MainActivity extends UnityPlayerNativeActivity {
    private static Context m_context;
    private static MainActivity mainActivity;
    private String m_launchInfo = "";
    private String m_objName = "";
    private String m_methodName = "";
    private String m_filePath = "";
    private String m_fileName = "temp.jpg";
    private String m_photoAlbumPath = "";

    private WeChat m_weChat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Uri uri = getIntent().getData();
        if (uri != null) {
            // 完整的url信息
            String url = uri.toString();
            if (url != "") {
                m_launchInfo = url;
                Log.d("Unity", "onCreate launchInfo:" + m_launchInfo);
                getIntent().setData(null);
            }
        }

        mainActivity = this;
        m_context = mainActivity.getApplicationContext();
        m_filePath = Environment.getExternalStorageDirectory()
                + "/Android/data/" + this.getPackageName() + "/files";
        File destDir1 = new File(m_filePath);
        if (!destDir1.exists()) {
            destDir1.mkdirs();
        }
        m_photoAlbumPath = Environment.getExternalStorageDirectory()
                + "/DCIM/Camera";
        File destDir = new File(m_photoAlbumPath);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
    }

    //从相册中选照片
    public void PhotoPick(String objName, String methodName) {
        m_objName = objName;
        m_methodName = methodName;
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 2);
    }

    //拍照
    public void PhotoTake(String objName, String methodName) {
        m_objName = objName;
        m_methodName = methodName;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 1);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            //从相机返回的数据
            if (requestCode == 1) {
                Bitmap bitmap = null;
                try {
                    bitmap = data.getExtras().getParcelable("data");
                } catch (Exception e) {
                    Log.d("Unity", "e: " + e.toString());
                }
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(m_filePath + "/" + m_fileName);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                try {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                UnityPlayer.UnitySendMessage(m_objName, m_methodName, m_fileName);
            }
            // 从相册返回的数据
            if (requestCode == 2) {
                if (data != null) {
                    ContentResolver resolver = getContentResolver();
                    // 得到图片的全路径
                    Uri uri = data.getData();
                    Bitmap bitmap = null;
                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(resolver, uri);
                    } catch (Exception e) {
                        Log.d("Unity", "e: " + e.toString());
                    }
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(m_filePath + "/" + m_fileName);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    try {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    UnityPlayer.UnitySendMessage(m_objName, m_methodName, m_fileName);
                } else {
                    UnityPlayer.UnitySendMessage(m_objName, m_methodName, "");
                }
            }
        } else {
            UnityPlayer.UnitySendMessage(m_objName, m_methodName, "");
        }
    }

    //图片插入相册 文件名含后缀
    public void PhotoInsert(final String imgName) {
        mainActivity.runOnUiThread(new Runnable() {
            public void run() {
                Bitmap bitmap = null;
                try {
                    bitmap = BitmapFactory.decodeFile(m_filePath + "/" + imgName);
                } catch (Exception e) {
                    Log.d("Unity", "e: " + e.toString());
                }
                File file = new File(m_photoAlbumPath, imgName);
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    Log.w("Unity", e.toString());
                }
                try {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    Log.w("Unity", e.toString());
                }
                bitmap.recycle();//扫描保存的图片
                m_context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory()
                        + "/DCIM/Camera/" + imgName)));
                Toast.makeText(m_context, "照片已保存到相册", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        Uri uri = getIntent().getData();
        if (uri != null) {
            // 完整的url信息
            String url = uri.toString();
            if (url != "") {
                m_launchInfo = url;
                Log.d("Unity", "onResume launchInfo:" + m_launchInfo);
                getIntent().setData(null);
            }
        }
    }

    //获取启动信息
    public void GetLaunchInfo(String objName, String methodName) {
        UnityPlayer.UnitySendMessage(objName, methodName, m_launchInfo);
        m_launchInfo = "";
    }

    //微信初始化
    public void WxInit(String appId) {
        Config.m_wechat_appid = appId;
        m_weChat = new WeChat();
        m_weChat.init(m_context, appId);
    }

    //微信登录
    public void WxLogin(String objName, String methodName) {
        m_weChat.login(objName, methodName);
    }

    //微信分享文字
    public void WxShareText(String text, int scene) {
        m_weChat.shareText(text, scene);
    }

    //微信分享图片
    public void WxShareImg(String imgName, int scene) {
        m_weChat.shareImg(imgName, scene);
    }

    //微信分享链接
    public void WxShareUrl(String url, String title, String description, String imgName, int scene) {
        m_weChat.shareUrl(url, title, description, imgName, scene);
    }

    //拷贝字符串到剪切板
    public void CopyString(String str) {
        ClipboardManager clipboard = (ClipboardManager) mainActivity.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("Label", str);
        clipboard.setPrimaryClip(clipData);
    }

    //打电话
    public void CallPhone(String phone) {
        try {
            // 构建一个隐式 intent ，intent 的 action 为 ACTION_CALL
            // ACTION_CALL 是系统内置的一个打电话的动作
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + phone));
            startActivity(intent);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }
}